package com.motorhome.manage.common.interceptor;

import com.motorhome.base.cache.MemcachedCache;
import com.motorhome.base.session.CookieSession;
import com.motorhome.base.util.StringUtil;
import com.motorhome.manage.common.statics.ManageStatics;
import com.motorhome.manage.dao.UserDao;
import com.motorhome.manage.domain.ManageUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: John
 */
public class ManageSessionInterceptor implements HandlerInterceptor {

    private static Logger logger = LoggerFactory.getLogger(ManageSessionInterceptor.class);

    @Autowired
    private MemcachedCache cache;

    @Autowired
    private UserDao userDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        logger.info("管理后台拦截器开始执行");

        CookieSession sessions = new CookieSession(request, response, ManageStatics.SESSION_KEY);
        String uid = sessions.get("uid");
        if (StringUtil.isBlank(uid)) {
            response.sendRedirect(request.getContextPath() + "/manage/login/toLogin");
            return false;
        }

        Long userId = Long.parseLong(uid);
        String key = "MANAGE_LOGIN_USER_" + userId;
        ManageUser manageUser = (ManageUser)cache.get(key);
        if (manageUser == null) {
            manageUser = userDao.queryUserById(userId);
            if (manageUser != null) {
                cache.set(key, manageUser, "24h");
            }
        }

        request.setAttribute("manageUser", manageUser);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {

        if (modelAndView != null) {
            modelAndView.addObject("baseFileUrl", ManageStatics.baseFileUrl);

            ManageUser manageUser = (ManageUser)request.getAttribute("manageUser");
            if (manageUser != null) {
                modelAndView.addObject("manageUser", manageUser);
            }
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {

        logger.info("管理后台拦截器执行结束");
    }

}
